import 'package:bigegg/common/log/xmm_log.dart';
import 'package:bigegg/common/log/xmm_logcat.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';

import '../../common/get/controller/xmm_base_controller.dart';
import '../../global/routes/xmm_routes.dart';
import '../../global/user/xmm_account_manager.dart';
import '../../utils/xmm_toast_util.dart';

class XmmLoginController extends XmmBaseGetxController {

  bool isLogging = false;

  void autoLogin() {
    if(isLogging) return;
    () async {
      try {
        isLogging = true;
        EasyLoading.show();
        XmmLogManger().putLog(XmmLogType.clickEvent, {'page': XmmLogPages.pageQuickLogin});
        bool isSuccess = await XmmAccountManager.instance.autoLogin();
        if (isSuccess) {
          Get.offAllNamed(XmmRoutes.mainPage);
        }
      } catch (e, s) {
        XmmXLogcat.d("auto login fail $e, $s");
      } finally {
        EasyLoading.dismiss();
        isLogging = false;
      }
    }();
  }

  void fastLogin() {
    if(isLogging) return;
    () async {
      try {
        isLogging = true;
        EasyLoading.show();
        XmmLogManger().putLog(XmmLogType.clickEvent, {'page': XmmLogPages.pageQuickLogin});
        bool isSuccess = await XmmAccountManager.instance.fastLogin();
        if (isSuccess) {
          Get.offAllNamed(XmmRoutes.mainPage);
        }
      } catch (e, s) {
        XmmXLogcat.d("fast login fail $e, $s");
        XmmToastUtils.show('Fast login failed, please try again later.');
      } finally {
        EasyLoading.dismiss();
        isLogging = false;
      }
    }();
  }

  void appleLogin() {
    if(isLogging) return;
    () async {
      try {
        isLogging = true;
        XmmLogManger().putLog(XmmLogType.clickEvent, {'page': XmmLogPages.pageAppleLogin});
        AuthorizationCredentialAppleID credential = await SignInWithApple.getAppleIDCredential(
          scopes: [
            AppleIDAuthorizationScopes.email,
            AppleIDAuthorizationScopes.fullName,
          ],
        );
        EasyLoading.show();
        bool isSuccess = await XmmAccountManager.instance
            .appleLogin(credential.identityToken);
        if (isSuccess) {
          Get.offAllNamed(XmmRoutes.mainPage);
        }
      } catch (e, s) {
        XmmXLogcat.d("apple login fail $e, $s");
        XmmToastUtils.show('Apple login failed, please try again later.');
      } finally {
        EasyLoading.dismiss();
        isLogging = false;
      }
    }();
  }
}
